<!--
 * @Descripttion: 
 * @Version: 
 * @Author: gaohj
 * @Date: 2022-10-28 15:57:11
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-10-28 16:25:30
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 输入一段字符串 输出每个字符在字符串中出现的次数 


        var arr1 = [1, 3, 2, 2, 2, 2, 2, 2, 4, 5, 5, 5, 6];
        //=> {1:1,2:6,3:1,4:1,5:3,6:1}

        // var person = {
        //     'name':'张三',
        //     'age':18,
        //     'height':'181cm',
        // }

        // // alert(person.name); // true
        // // alert(person.age); // true 
        // // alert(person.height); // true

        // alert(person.weight); // false 
        var map1 = {};
        for (var i = 0; i < arr1.length; i++) {
            var key = arr1[i]; // 每个元素作为对象的键
            if (map1[key]) {
                map1[key] += 1;
            } else {
                map1[key] = 1;
            }
        }
        console.log(map1);

        /**
         * @function: arr_to_object
         * @description: 统计数组中每个元素出现的次数
         * @return {Object} {1:2,2:6}
         * @author: gaohj
         * @example: arr_to_object([1,1,2,2,2,2,2,2])
         */        

        function arr_to_object(arr) {
            var map1 = {};
            for (var i = 0; i < arr.length; i++) {
                var key = arr[i]; // 每个元素作为对象的键
                if (map1[key]) {
                    map1[key] += 1;
                } else {
                    map1[key] = 1;
                }
            }
            return map1
        }


        function str_to_object(strs) {
            var map1 = {};// 创建一个空对象 存放最终的结果
            for (var i = 0; i < strs.length; i++) {
                var key = strs[i]; // 每个元素作为对象的键
                if (map1[key]) {  // if中要使用对象[键]这种方式
                    map1[key] += 1;
                } else {
                    map1[key] = 1;
                }
            }
            return map1
        }


        var content = prompt('请输入你的内容:')
        var res = str_to_object(content);
        for(var i in res){
            console.log(i,'出现了',res[i],'次');
        }
        
    </script>
</body>

</html>